package de.hbrs.ooka.dhs.persistence;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaQuery;

public abstract class DatabaseManager<T> {

    private Class<T> entityClass;
    private EntityManager entityManager;

    public DatabaseManager(Class<T> entityClass) {
        this.entityClass = entityClass;
		entityManager = (EntityManager) Persistence.createEntityManagerFactory("DHSComponentRuntimePU").createEntityManager();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> findAll() {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(getEntityClass()));
        return getEntityManager().createQuery(cq).getResultList();
    }
    
    public void create(T entity){
		entityManager.getTransaction().begin();
		entityManager.persist(entity);
		entityManager.getTransaction().commit();
	}
	
	public T update(T entity){
		entityManager.getTransaction().begin();
		entityManager.merge(entity);
		entityManager.getTransaction().commit();
		
		return entity;
	}
	
	public void remove(T entity){
		entityManager.getTransaction().begin();
		entityManager.remove(entity);
		entityManager.getTransaction().commit();
	}


	public Class<T> getEntityClass() {
		return entityClass;
	}


	public void setEntityClass(Class<T> entityClass) {
		this.entityClass = entityClass;
	}


	public EntityManager getEntityManager() {
		return entityManager;
	}


	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
    
}

